package model

import (
	"strings"
	"time"
)

// APIForwardConfig API转发配置
type APIForwardConfig struct {
	ID          uint      `json:"id" gorm:"primaryKey"`
	APIPath     string    `json:"api_path" gorm:"uniqueIndex;not null;comment:API路径"`
	TargetURL   string    `json:"target_url" gorm:"not null;comment:目标转发URL"`
	ChannelID   uint      `json:"channel_id" gorm:"default:0;comment:转发渠道ID，优先使用渠道的base_url"`
	ModelName   string    `json:"model_name" gorm:"type:varchar(255);default:'';comment:用于日志展示的模型名称"`
	Cost        float64   `json:"cost" gorm:"not null;comment:每次调用费用"`
	IsActive    bool      `json:"is_active" gorm:"default:true;comment:是否启用"`
	Description string    `json:"description" gorm:"comment:描述信息"`
	CreatedAt   time.Time `json:"created_at"`
	UpdatedAt   time.Time `json:"updated_at"`
}

// TableName 指定表名
func (APIForwardConfig) TableName() string {
	return "api_forward_configs"
}

// GetActiveForwardConfigs 获取所有启用的转发配置
func GetActiveForwardConfigs() ([]*APIForwardConfig, error) {
	var configs []*APIForwardConfig
	err := DB.Where("is_active = ?", true).Find(&configs).Error
	return configs, err
}

// GetForwardConfigByPath 根据API路径获取转发配置
func GetForwardConfigByPath(apiPath string) (*APIForwardConfig, error) {
	trimPath := strings.TrimSpace(apiPath)
	var config APIForwardConfig
	err := DB.Where("api_path = ? AND is_active = ?", trimPath, true).First(&config).Error
	if err == nil {
		return &config, nil
	}
	// fallback: 遍历激活配置，做去空白后的等值匹配，兼容历史数据中的不可见字符
	var configs []*APIForwardConfig
	if e := DB.Where("is_active = ?", true).Find(&configs).Error; e != nil {
		return nil, err
	}
	for _, c := range configs {
		if strings.TrimSpace(c.APIPath) == trimPath {
			return c, nil
		}
	}
	return nil, err
}

// CreateForwardConfig 创建转发配置
func CreateForwardConfig(config *APIForwardConfig) error {
	return DB.Create(config).Error
}

// UpdateForwardConfig 更新转发配置
func UpdateForwardConfig(config *APIForwardConfig) error {
	return DB.Save(config).Error
}

// DeleteForwardConfig 删除转发配置
func DeleteForwardConfig(id uint) error {
	return DB.Delete(&APIForwardConfig{}, id).Error
}

// GetAllForwardConfigs 获取所有转发配置（分页）
func GetAllForwardConfigs(page, pageSize int) ([]*APIForwardConfig, int64, error) {
	var configs []*APIForwardConfig
	var total int64

	err := DB.Model(&APIForwardConfig{}).Count(&total).Error
	if err != nil {
		return nil, 0, err
	}

	err = DB.Offset((page - 1) * pageSize).Limit(pageSize).Find(&configs).Error
	return configs, total, err
}
